#include "CodeTableEditUI.h"
#include <FL/fl_ask.H>
#include "utils/ui_utils.h"

CodeTableEditUI::CodeTableEditUI(UIIpcClient* ui_ipc_client) 
    : _ui_ipc_client(ui_ipc_client) 
{
    
}

CodeTableEditUI::~CodeTableEditUI() {
    // 关闭窗口
    if(_codetable_edit_view.main_window) {
        _codetable_edit_view.main_window->hide();
    }
}

//=== 在初始化函数中添加新增窗口的回调 ===//
void CodeTableEditUI::init(){
    // 初始化UI
    _codetable_edit_view.make_window();
    _codetable_edit_view.main_window->hide(); // 初始隐藏

    _add_word_view.make_window(); // 初始化新增词条窗口
    _add_word_view.main_window->hide(); // 初始隐藏

    _codetable_edit_view.browser_words->type(FL_HOLD_BROWSER); // 单选模式

    // 初始化FLTK组件回调
    _codetable_edit_view.btn_search->callback(onSearchWords, this);
    _codetable_edit_view.btn_add->callback(onAddWord, this);
    _codetable_edit_view.btn_remove->callback(onRemoveWord, this);
    _codetable_edit_view.btn_up->callback(onMoveUpWord, this);
    _codetable_edit_view.btn_down->callback(onMoveDownWord, this);

    // 新增词条窗口回调
    _add_word_view.btn_add->callback(onAddWordConfirm, this);
    _add_word_view.btn_cancel->callback(onAddWordCancel, this);
}

//=== 添加词条界面回调实现 ===//
void CodeTableEditUI::onAddWord(Fl_Widget*, void* userdata) {
    auto self = static_cast<CodeTableEditUI*>(userdata);

    // if(self->_search_code.empty()) {
    //     fl_alert("请先搜索编码！");
    //     return;
    // }

    // 显示新增词条窗口
    self->_add_word_view.input_code->value(self->_search_code.c_str());  
    self->_add_word_view.input_word->value("");  // 清空词语输入
    UIUtils::showFlDoubleWindow(self->_add_word_view.main_window);
}

void CodeTableEditUI::onAddWordConfirm(Fl_Widget*, void* userdata) {
    auto self = static_cast<CodeTableEditUI*>(userdata);
    const std::string code = self->_add_word_view.input_code->value();
    const std::string word = self->_add_word_view.input_word->value();

    if(code.empty() || word.empty()){
        fl_alert("编码和词语不能为空！");
        return;
    }

    for(int i = 0;i<code.size();i++){
        if(code[i] < 'a' || code[i] > 'z'){
            fl_alert("编码只能是小写字母！");
            return;
        }
    }

    unsigned int newCodeId = 0;
    if(self->_ui_ipc_client->getMsgHelper()->addWord(
        self->_current_code_table_id, code, word, newCodeId))
    {
        // 添加成功后隐藏窗口
        self->_add_word_view.main_window->hide();
        self->_codetable_edit_view.input_code->value(code.c_str());
        // 刷新主界面
        self->onSearchWords(nullptr, userdata); 
    }
    else {
        fl_alert("添加词条失败！");
    }
}

void CodeTableEditUI::onAddWordCancel(Fl_Widget*, void* userdata) {
    auto self = static_cast<CodeTableEditUI*>(userdata);
    self->_add_word_view.main_window->hide();
}

void CodeTableEditUI::show(unsigned int code_table_id, const std::string &window_title) {
    _current_code_table_id = code_table_id;
    _search_code.clear();

    _codetable_edit_view.browser_words->clear();
    _codetable_edit_view.input_code->value("");
    _words.clear();
    

    // 设置窗口标题
    _codetable_edit_view.main_window->label(window_title.c_str());
    UIUtils::showFlDoubleWindow(_codetable_edit_view.main_window);
}

//=== 回调函数实现 ===//
void CodeTableEditUI::onSearchWords(Fl_Widget*, void* userdata) {
    auto self = static_cast<CodeTableEditUI*>(userdata);
    
    // 获取输入编码
    const char* code = self->_codetable_edit_view.input_code->value();
    
    if(code == nullptr || code[0] == '\0') {
        fl_alert("请输入编码！");
        return;
    }

    self->_search_code = code;
    
    // 清空并刷新浏览器
    self->_codetable_edit_view.browser_words->clear();
    self->_words.clear();

    // 通过IPC查询词条
    if(self->_ui_ipc_client->getMsgHelper()->getCodeTableDataByCode(
        self->_current_code_table_id, code, self->_words))
    {
        for(const auto& item : self->_words) {
            self->_codetable_edit_view.browser_words->add(item.word.c_str());
        }
    }
}

void CodeTableEditUI::onRemoveWord(Fl_Widget*, void* userdata) {
    auto self = static_cast<CodeTableEditUI*>(userdata);
    
    // 获取选中项（行号从1开始）
    int line = self->_codetable_edit_view.browser_words->value();
    if(line < 1) return;
    
    // 获取对应数据
    WubiCodetableData& data = self->_words[line-1];
    
    if(self->_ui_ipc_client->getMsgHelper()->removeWord(data.id)) {
        self->_words.erase(self->_words.begin() + (line-1));
        self->_codetable_edit_view.browser_words->remove(line);
    }
}

void CodeTableEditUI::onMoveUpWord(Fl_Widget*, void* userdata) {
    auto self = static_cast<CodeTableEditUI*>(userdata);
    
    int line = self->_codetable_edit_view.browser_words->value();
    if(line < 2) return;

    // 获取需要交换的词条ID
    unsigned int id1 = self->_words[line-1].id;
    unsigned int id2 = self->_words[line-2].id;
    
    // 调用服务器接口交换顺序
    if(self->_ui_ipc_client->getMsgHelper()->swapCodeTableDataOrder(
        self->_current_code_table_id, id1, id2)) 
    {
        // 服务器操作成功后再更新本地数据
        std::swap(self->_words[line-1], self->_words[line-2]);
        self->refreshBrowser();
        self->_codetable_edit_view.browser_words->select(line-1);
    }
    else {
        fl_alert("词条顺序更新失败！");
    }
}

void CodeTableEditUI::onMoveDownWord(Fl_Widget*, void* userdata) {
    auto self = static_cast<CodeTableEditUI*>(userdata);
    
    int line = self->_codetable_edit_view.browser_words->value();
    if(line < 1 || line >= self->_words.size()) return;

    // 获取需要交换的词条ID
    unsigned int id1 = self->_words[line-1].id;
    unsigned int id2 = self->_words[line].id;
    
    // 调用服务器接口交换顺序
    if(self->_ui_ipc_client->getMsgHelper()->swapCodeTableDataOrder(
        self->_current_code_table_id, id1, id2)) 
    {
        // 服务器操作成功后再更新本地数据
        std::swap(self->_words[line-1], self->_words[line]);
        self->refreshBrowser();
        self->_codetable_edit_view.browser_words->select(line+1);
    }
    else {
        fl_alert("词条顺序更新失败！");
    }
}

//=== 辅助函数 ===//
void CodeTableEditUI::refreshBrowser() {
    _codetable_edit_view.browser_words->clear();
    for(const auto& word : _words) {
        _codetable_edit_view.browser_words->add(word.word.c_str());
    }
}